package com.bjgov.scoresys.action;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.MappingDispatchAction;

import com.bjgov.scoresys.entity.Project;
import com.bjgov.scoresys.entity.ProjectItems;
import com.bjgov.scoresys.entity.ScoreHistory;
import com.bjgov.scoresys.entity.ScoreItem;
import com.bjgov.scoresys.entity.ScoreTree;
import com.bjgov.scoresys.entity.User;
import com.bjgov.scoresys.entity.UserProject;
import com.bjgov.scoresys.form.CalculateProjectScoreForm;
import com.bjgov.scoresys.form.ProjectForm;
import com.bjgov.scoresys.form.ProjectTmpItemsForm;
import com.bjgov.scoresys.resource.UserKey;
import com.bjgov.scoresys.service.ProjectHandler;
import com.bjgov.scoresys.service.ProjectItemsHandler;
import com.bjgov.scoresys.service.ScoreHistoryHandler;
import com.bjgov.scoresys.service.ScoreSubItemsHandler;
import com.bjgov.scoresys.service.ScoreTreeHandler;
import com.bjgov.scoresys.service.UserHandler;
import com.bjgov.scoresys.service.UserProjectHandler;
import com.bjgov.scoresys.util.DateUtil;
import com.bjgov.scoresys.util.RequestUtil;

public class ProjectAction extends MappingDispatchAction {

	private static Log logger = LogFactory.getLog(ProjectAction.class);

	/**
	 * 增加项目
	 */
	public ActionForward addProject(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		User user = (User) request.getSession().getAttribute("user");
		ProjectForm projectform = (ProjectForm) form;
		Project entity = new Project();
		entity.setUserId(user.getId());
		entity.setName(projectform.getName());
		entity.setBuildUnit(projectform.getBuildUnit());
		entity.setConstructUnit(projectform.getConstructUnit());
		entity.setDesignUnit(projectform.getDesignUnit());
		entity.setSupervisorUnit(projectform.getSupervisorUnit());
		entity.setStartTime(DateUtil.getDate(projectform.getStartTime(),
				"yyyy-MM-dd"));
		// entity.setEndTime(projectform.getEndTime());
		entity.setScoreUser(projectform.getScoreUsers());
		entity.setCreateDate(new Date());
		entity.setStatus((short) 0);
		int id = ProjectHandler.addProject(entity);

		if (!StringUtils.isEmpty(projectform.getScoreUsers())) {
			String[] userIdArr = projectform.getScoreUsers().split(",");
			for (int i = 0; i < userIdArr.length; i++) {
				UserProject up = new UserProject();
				up.setProject(ProjectHandler.getProject(id));
				up.setStatus((short) 0);
				up.setUser(UserHandler.getUser(Integer.parseInt(userIdArr[i])));
				UserProjectHandler.save(up);
			}
		}

		ProjectHandler.sendProject(id, projectform.getName());

		ActionForward af = mapping.findForward("success");
		ActionForward afnew = new ActionForward();
		afnew.setRedirect(true);
		afnew.setPath(af.getPath() + "?id=" + id);
		return afnew;
	}

	/**
	 * 修改项目,评分用户可能会改变 同时更新用户评分表
	 **/
	public ActionForward editProject(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		User user = (User) request.getSession().getAttribute("user");
		ProjectForm projectform = (ProjectForm) form;
		int id = projectform.getId();
		Project entity = ProjectHandler.getProject(id);

		entity.setUserId(user.getId());
		entity.setName(projectform.getName());
		entity.setConstructUnit(projectform.getConstructUnit());
		entity.setSupervisorUnit(projectform.getSupervisorUnit());
		entity.setBuildUnit(projectform.getBuildUnit());
		entity.setDesignUnit(projectform.getDesignUnit());
		entity.setStartTime(DateUtil.getDate(projectform.getStartTime(),
				"yyyy-MM-dd"));
		entity.setScoreUser(projectform.getScoreUsers());
		entity.setCreateDate(new Date());
		entity.setStatus((short) 0);
		ProjectHandler.addProject(entity);

		// 删除原来评分人员
		Set<UserProject> oldUserProject = entity.getUserProjects();
		if (oldUserProject != null) {
			entity.setUserProjects(null);
			for (UserProject p : oldUserProject) 
			{
				UserProjectHandler.delete(p);
			}
		}
		
		if (!StringUtils.isEmpty(projectform.getScoreUsers())) {
			String[] userIdArr = projectform.getScoreUsers().split(",");
			for (int i = 0; i < userIdArr.length; i++) {
				UserProject up = new UserProject();
				up.setProject(ProjectHandler.getProject(id));
				up.setStatus((short) 0);
				up.setUser(UserHandler.getUser(Integer.parseInt(userIdArr[i])));
				UserProjectHandler.save(up);
			}
		}
		
		ProjectHandler.sendProject(id, projectform.getName());

		ActionForward af = mapping.findForward("success");
		ActionForward afnew = new ActionForward();
		afnew.setRedirect(true);
		afnew.setPath(af.getPath() + "?id=" + id);
		return afnew;
	}

	/**
	 * 添加评分项
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward addProjectItem(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		ProjectTmpItemsForm itemsForm = (ProjectTmpItemsForm) form;
		float totalScore = 0.0f;
		int topTreeId = Integer.parseInt(ScoreTreeHandler
				.loadById(itemsForm.getTreeId()).getDeepPath().split(",")[0]);

		ScoreTree controlTree = ScoreTreeHandler.getControlTreeByTree(itemsForm
				.getTreeId());
		// TODO
		int controlId = controlTree.getId();

		// 取出当前已经有的分数，再加了form的分数，看看是不是大于controlTree的分类
		Project project = ProjectHandler.getProject(itemsForm.getProjectId());
		// Set<ProjectItems> projectItems = project.getProjectItemses();
		// List<ProjectItems> projectItems=
		// ProjectItemsHandler.getByProjectIdControlId(itemsForm.getProjectId(),
		// controlId);
		// //计算已添加分数
		// if(projectItems!=null && projectItems.size()>0)
		// {
		// for(ProjectItems pi:projectItems)
		// {
		// totalScore = totalScore+pi.getScore();
		// }
		// }

		totalScore = ProjectItemsHandler.getControlIdScoreSum(
				itemsForm.getProjectId(), controlId);

		// 计算提交分数
		Float[] tempScore = itemsForm.getScore();
		for (int i = 0; i < tempScore.length; i++) {
			totalScore = totalScore + tempScore[i];// int + float自动转成float
		}

		if (controlTree != null && totalScore > controlTree.getPercent()) {
			request.setAttribute("message", "评分项之和大于总分，评分设置有误，请更正!");
			request.setAttribute(
					"returnURL",
					"/project/addNewProject_StepTwoNew.jsp?id="
							+ itemsForm.getProjectId() + "&treeId="
							+ itemsForm.getTreeId());
			return mapping.findForward("fail");
		} else {
			int[] selectItems = itemsForm.getSelectItems();
			for (int i = 0; i < selectItems.length; i++) {
				ProjectItems item = new ProjectItems();
				item.setProject(project);
				item.setScoreItem(ScoreSubItemsHandler.loadByID(itemsForm
						.getSelectItems()[i]));
				item.setScore(tempScore[i]);
				item.setTopCateId(topTreeId);
				item.setControlId(controlId);
				ProjectItemsHandler.save(item);
			}

			request.setAttribute("message", "添加成功！");
			request.setAttribute("nextURL",
					mapping.getInput() + "?id=" + itemsForm.getProjectId()
							+ "&treeId=" + itemsForm.getTreeId());
			return mapping.findForward("tip");
		}
	}

	/*
	 * 修改评分项
	 */
	public ActionForward editProjectItem(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		ProjectTmpItemsForm itemsForm = (ProjectTmpItemsForm) form;
		float totalScore = 0.0f;
		int topTreeId = Integer.parseInt(ScoreTreeHandler.loadById(itemsForm.getTreeId()).getDeepPath().split(",")[0]);

		ScoreTree controlTree = ScoreTreeHandler.getControlTreeByTree(itemsForm.getTreeId());
		// 取出当前已经有的分数，再加了form的分数，看看是不是大于controlTree的分类
		Project project = ProjectHandler.getProject(itemsForm.getProjectId());
		Set<ProjectItems> projectItems = project.getProjectItemses();
		int[] id = itemsForm.getId();

		int controlId = controlTree.getId();
		String where = "";
		for (int i = 0; i < id.length; i++) {
			where = where + "," + id[i];
		}
		if (where.trim().length() > 0) {
			where = where.substring(1);
			totalScore = ProjectItemsHandler.getNochangeIdScoreSum(where,controlId,itemsForm.getProjectId());
		}

		// //计算已添加分数
		// boolean isCruuentID = false;//要重新计算分值的ID是不是当前要修改的ID，如果是，不算在总分内
		// if(projectItems!=null && projectItems.size()>0)
		// {
		// for(ProjectItems pi:projectItems)
		// {
		// for(int i=0;i<id.length;i++)
		// {
		// if(id[i]==pi.getId())
		// {
		// isCruuentID=true;
		// break;
		// }
		// }
		// if(!isCruuentID)
		// {
		// totalScore = totalScore+pi.getScore();
		// isCruuentID = false;
		// }
		// }
		//
		// }
		// 计算提交分数
		Float[] tempScore = itemsForm.getScore();
		for (int i = 0; i < tempScore.length; i++) {
			totalScore = totalScore + tempScore[i];// int + float自动转成float
		}

		if (controlTree != null && totalScore > controlTree.getPercent()) {
			request.setAttribute("message", "评分项之和大于总分，评分设置有误，请更正!");
			request.setAttribute(
					"returnURL",
					"/project/addNewProject_StepTwoNew.jsp?id="
							+ itemsForm.getProjectId() + "&treeId="
							+ itemsForm.getTreeId());
			return mapping.findForward("fail");
		} else {
			int[] selectItems = itemsForm.getSelectItems();
			for (int i = 0; i < selectItems.length; i++) {
				ProjectItems item = ProjectItemsHandler.loadByID(id[i]);
				item.setProject(project);
				item.setScoreItem(ScoreSubItemsHandler.loadByID(itemsForm
						.getSelectItems()[i]));
				item.setScore(tempScore[i]);
				item.setTopCateId(topTreeId);
				item.setControlId(controlId);
				ProjectItemsHandler.save(item);
			}
			// ActionForward af = mapping.findForward("success");
			// ActionForward afnew = new ActionForward();
			// afnew.setRedirect(true);
			// afnew.setPath(af.getPath() + "?id=" + itemsForm.getProjectId() +
			// "&treeId=" + itemsForm.getTreeId());
			// return afnew;

			request.setAttribute("message", "修改成功！");
			request.setAttribute("nextURL",
					mapping.getInput() + "?id=" + itemsForm.getProjectId()
							+ "&treeId=" + itemsForm.getTreeId());
			return mapping.findForward("tip");

		}
	}
	
	
	/**
	 * 生成项目评分 --form里可以考虑把总分带过来
	 * 几个要素，treeid,控制节点，质量控制点，占百分比，总分
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward calculateProjectScore(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		CalculateProjectScoreForm calculateForm = (CalculateProjectScoreForm) form;
		int projectID = calculateForm.getProjectId();
		Project project = ProjectHandler.getProject(projectID);
		String[] scoreitem = calculateForm.getScoreitem();
		if(scoreitem.length>0)
		{
			Map<Integer,List<ScoreTree>> controlTreeMap = new HashMap<Integer,List<ScoreTree>>();
			for(int i=0;i<scoreitem.length;i++)
			{
				String treeIDStr = scoreitem[i];
				if(treeIDStr.indexOf(",")>-1)
				{
					String[] temptreeIDStr = treeIDStr.split(",");
					int treeID = Integer.parseInt(temptreeIDStr[temptreeIDStr.length-1]);//找出treeid
					ScoreTree controlTree = ScoreTreeHandler.getControlTreeByTree(treeID);//找出当前tree的控制节点
					if(!controlTree.getIsControl())
					{
						continue;//如果不是控制树，接着循环
					}
					ScoreTree scoreTree = ScoreTreeHandler.loadById(treeID);
					List<ScoreTree> listTemp =  new ArrayList<ScoreTree>();
					if(controlTreeMap.containsKey(controlTree.getId()))
					{
						listTemp = controlTreeMap.get(controlTree.getId());
					}
					if(scoreTree.getHasScoreItem())
					{
						listTemp.add(scoreTree);
						controlTreeMap.put(controlTree.getId(), listTemp);//装入所有控制节点下的含有最终质量控制点节点
					}
				}
			}
			if(controlTreeMap.size()>0)
			{
				Iterator it = controlTreeMap.keySet().iterator();
				while(it.hasNext())
				{
					Integer key = (Integer)it.next();
					ScoreTree treePercent = ScoreTreeHandler.loadById(key);
					float currentKeyScoreCount = treePercent.getPercent();//获取当前树的总分
					int currentHasItemCount = 0;//一共有多少个质量控制点
					float projectItemScore = 0.0f;//每个控制点平均分
					float AvgScore = 0.0f;//保留二位小数点平均分
					List<ScoreTree> listHasItems = controlTreeMap.get(key);
					for(ScoreTree st:listHasItems)
					{
						Set<ScoreItem> item = st.getScoreItems();
						currentHasItemCount+=item.size();
					}
					if(currentHasItemCount!=0)
					{
						projectItemScore = currentKeyScoreCount/currentHasItemCount;
//						BigDecimal b = new BigDecimal(projectItemScore);
//						AvgScore = b.setScale(4, BigDecimal.ROUND_HALF_UP)
//								.floatValue();
					}
					else
					{
						continue;
					}
					
					for(ScoreTree st:listHasItems)
					{
						Set<ScoreItem> item = st.getScoreItems();
						for(ScoreItem scoreItem:item)
						{
							int itemsTreeID=scoreItem.getScoreTree().getId();
							int topTreeId = Integer.parseInt(ScoreTreeHandler.loadById(itemsTreeID).getDeepPath().split(",")[0]);
							ScoreTree controlTree = ScoreTreeHandler.getControlTreeByTree(itemsTreeID);
							
							ProjectItems projectItem = new ProjectItems();
							projectItem.setProject(project);
							projectItem.setScoreItem(scoreItem);
							projectItem.setScore(projectItemScore);
							projectItem.setTopCateId(topTreeId);
							projectItem.setControlId(controlTree.getId());
							ProjectItemsHandler.save(projectItem);
						}
					}
				}
			}
		}
		
		ActionForward af = mapping.findForward("success");
		ActionForward afnew = new ActionForward();
		afnew.setRedirect(true);
		afnew.setPath(af.getPath() + "?id=" + calculateForm.getProjectId()+ "&treeId=0");
		return afnew;
	}

	/**
	 * 重新计算项目评分
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward reCalculateProjectScore(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String treeIDArray = "";
		String[] scoreitem = null;
		int projectID = Integer.parseInt(request.getParameter("projectid"));
		Project project = ProjectHandler.getProject(projectID);
		List<ProjectItems> list = ProjectItemsHandler.getByProject(projectID);
		if (list != null && list.size() > 0) {
			List<Integer> listTreeID = new ArrayList<Integer>();
			for (int ii = 0; ii < list.size(); ii++) {
				if(!listTreeID.contains(list.get(ii).getScoreItem().getScoreTree().getId()))
				{
					listTreeID.add(list.get(ii).getScoreItem().getScoreTree().getId());
					treeIDArray = treeIDArray+ list.get(ii).getScoreItem().getScoreTree().getId();
					if (ii < list.size()-1)
						treeIDArray += ",";
				}
			}
			
			treeIDArray = treeIDArray.substring(0,treeIDArray.length()-1);
			
			
			for (ProjectItems item : list) {
				ProjectItemsHandler.delete(item);
			}

			scoreitem = treeIDArray.split(",");
			if (scoreitem.length > 0) {
				Map<Integer, List<ScoreTree>> controlTreeMap = new HashMap<Integer, List<ScoreTree>>();
				for (int i = 0; i < scoreitem.length; i++) {
					int treeID = Integer.parseInt(scoreitem[i]);// 找出treeid
					ScoreTree controlTree = ScoreTreeHandler
							.getControlTreeByTree(treeID);// 找出当前tree的控制节点
					if (!controlTree.getIsControl()) {
						continue;// 如果不是控制树，接着循环
					}
					ScoreTree scoreTree = ScoreTreeHandler.loadById(treeID);
					List<ScoreTree> listTemp = new ArrayList<ScoreTree>();
					if (controlTreeMap.containsKey(controlTree.getId())) {
						listTemp = controlTreeMap.get(controlTree.getId());
					}
					if (scoreTree.getHasScoreItem()) {
						listTemp.add(scoreTree);
						controlTreeMap.put(controlTree.getId(), listTemp);// 装入所有控制节点下的含有最终质量控制点节点
					}
				}
				if (controlTreeMap.size() > 0) {
					Iterator it = controlTreeMap.keySet().iterator();
					while (it.hasNext()) {
						Integer key = (Integer) it.next();
						ScoreTree treePercent = ScoreTreeHandler.loadById(key);
						float currentKeyScoreCount = treePercent.getPercent();// 获取当前树的总分
						int currentHasItemCount = 0;// 一共有多少个质量控制点
						double projectItemScore = 0.0f;// 每个控制点平均分
						float AvgScore = 0.0f;// 保留二位小数点平均分
						List<ScoreTree> listHasItems = controlTreeMap.get(key);
						for (ScoreTree st : listHasItems) {
							Set<ScoreItem> item = st.getScoreItems();
							currentHasItemCount += item.size();
						}
						if (currentHasItemCount != 0) {
							projectItemScore = currentKeyScoreCount
									/ currentHasItemCount;
							// BigDecimal b = new
							// BigDecimal(projectItemScore);
							// AvgScore = b.setScale(4,
							// BigDecimal.ROUND_HALF_UP).floatValue();
							AvgScore = (float)projectItemScore;
						} else {
							continue;
						}

						for (ScoreTree st : listHasItems) {
							Set<ScoreItem> item = st.getScoreItems();
							for (ScoreItem scoreItem : item) {
								int itemsTreeID = scoreItem.getScoreTree()
										.getId();
								int topTreeId = Integer
										.parseInt(ScoreTreeHandler
												.loadById(itemsTreeID)
												.getDeepPath().split(",")[0]);
								ScoreTree controlTree = ScoreTreeHandler
										.getControlTreeByTree(itemsTreeID);

								ProjectItems projectItem = new ProjectItems();
								projectItem.setProject(project);
								projectItem.setScoreItem(scoreItem);
								projectItem.setScore(AvgScore);
								projectItem.setTopCateId(topTreeId);
								projectItem.setControlId(controlTree.getId());
								ProjectItemsHandler.save(projectItem);
							}
						}
					}
				}
			}
		}
		request.setAttribute("message", "重新计算项目分数成功");
		request.setAttribute("nextURL", "ProjectView.jsp?projectId="
				+ projectID + "&treeId=0");
		return mapping.findForward("tip");

	}

	/**
	 * 保存项目临时条目
	 */
	public ActionForward addProjectTmpItem(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ProjectTmpItemsForm itemsForm = (ProjectTmpItemsForm) form;
		float totalScore = 0.0f;
		// int treeId = RequestUtil.getIntParameter(request, "oldTreeId", 0);
		int topTreeId = Integer.parseInt(ScoreTreeHandler
				.loadById(itemsForm.getTreeId()).getDeepPath().split(",")[0]);
		ScoreTree controlTree = ScoreTreeHandler.getControlTreeByTree(itemsForm
				.getTreeId());
		Project project = ProjectHandler.getProject(itemsForm.getProjectId());
		Map<Integer, List<ProjectItems>> tmpItem = (Map<Integer, List<ProjectItems>>) request
				.getSession().getAttribute("tmp_projectitem");
		if (tmpItem == null)
			tmpItem = new HashMap<Integer, List<ProjectItems>>();
		List<ProjectItems> list = new ArrayList<ProjectItems>();
		if (itemsForm.getSelectItems() != null
				&& itemsForm.getSelectItems().length > 0) {
			for (int i = 0; i < itemsForm.getSelectItems().length; i++) {
				ProjectItems item = new ProjectItems();
				item.setScoreItem(ScoreSubItemsHandler.loadByID(itemsForm
						.getSelectItems()[i]));
				item.setProject(project);
				item.setScore(RequestUtil.getFloatParameter(request,
						"itemScore_" + itemsForm.getSelectItems()[i], 0.0f));
				totalScore += item.getScore();
				item.setTopCateId(topTreeId);
				list.add(item);
			}
		}
		tmpItem.put(itemsForm.getTreeId(), list);
		request.getSession().setAttribute("tmp_projectitem", tmpItem);
		if (controlTree != null && totalScore != controlTree.getPercent()) {
			request.setAttribute("message", "评分项之和不等于总分，评分设置有误，请更正!");
			request.setAttribute(
					"returnURL",
					"/project/addNewProject_StepTwo.jsp?id="
							+ itemsForm.getProjectId() + "&treeId="
							+ itemsForm.getTreeId());
			return mapping.findForward("fail");
		} else {
			ActionForward af = mapping.findForward("success");
			ActionForward afnew = new ActionForward();
			// afnew.setRedirect(true);
			afnew.setPath(af.getPath() + "?id=" + itemsForm.getProjectId()
					+ "&treeId=" + itemsForm.getTreeId());
			return afnew;
		}
	}

	/**
	 * 完成项目创建
	 */
	/*public ActionForward completeCreateProject(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		User user = (User) request.getSession().getAttribute("user");
		int projectId = RequestUtil.getIntParameter(request, "projectId", 0);
		Map<Integer, List<ProjectItems>> tmpItem = (Map<Integer, List<ProjectItems>>) request
				.getSession().getAttribute("tmp_projectitem");
		for (Integer key : tmpItem.keySet()) {
			List<ProjectItems> list = tmpItem.get(key);
			for (int i = 0; i < list.size(); i++) {
				// ProjectItems item = list.get(i);
				ProjectItemsHandler.save(list.get(i));
			}
		}

		Project entity = ProjectHandler.getProject(projectId);
		entity.setStatus((short) 1);
		ProjectHandler.updateProject(entity);
		return mapping.findForward("success");
	}*/
	
	
	public ActionForward completeCreateProject(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		ProjectTmpItemsForm itemsForm = (ProjectTmpItemsForm) form;
		
		int projectId = itemsForm.getProjectId();
		Project entity = ProjectHandler.getProject(projectId);
	    entity.setStatus((short)1);
	    ProjectHandler.updateProject(entity);
	    return mapping.findForward("success");
	}

	public ActionForward deleteProject(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String[] strIdArr = request.getParameterValues("selectItems");
		for (String s : strIdArr) {
			ProjectHandler
					.delete(ProjectHandler.getProject(Integer.parseInt(s)));
		}
		request.setAttribute("message", "删除评分项目成功");
		request.setAttribute("nextURL", mapping.getInput());
		return mapping.findForward("tip");
	}
	
	/**
	 * 删除评分子项
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward deleteProjectItem(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		int projectid = Integer.parseInt(request.getParameter("projectid"));
		int treeid = Integer.parseInt(request.getParameter("itemid"));
		List<ProjectItems> list = ProjectItemsHandler.getByProjectIdTreeId(
				projectid, treeid);
		if (list != null && list.size() > 0)
			for (ProjectItems item : list) {
				ProjectItemsHandler.delete(item);
			}
		request.setAttribute("message", "删除评分子项成功");
		request.setAttribute("nextURL", "ProjectView.jsp?projectId="
				+ projectid + "&treeId=0");
		return mapping.findForward("tip");
	}	
	
	
	/**
	 * 完成项目评分，如果有用户没有完成评分，则提示评成没有完成，不能结束项目----此处需要修改
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ActionForward completeProjectScore(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		int projectId = RequestUtil.getIntParameter(request, "id", 0);
		User user = (User) request.getSession().getAttribute("user");
		if(projectId==0) {
			request.setAttribute("message", "要结束评分的项目不存在");
			request.setAttribute("returnURL", mapping.getInput());
			return mapping.findForward("fail");	
		}
		Project entity = ProjectHandler.getProject(projectId);
	    
	    
	    //获得用户项目表，找到所有已评完分的用户，计算他们的评分值，根据人数得出评分的平均值
	    Set<UserProject> upList = entity.getUserProjects();
	    
	    boolean doneScore=true;
	    for(UserProject up:upList)
	    {
	    	if(up.getStatus()!=2)
	    	{
	    		doneScore=false;
	    		break;
	    	}
	    }
	    
	    if(!doneScore)
	    {
	    	request.setAttribute("message", "该项目评分人还没有完成评分，暂时不能结束！");
			request.setAttribute("returnURL", mapping.getInput());
			return mapping.findForward("fail");
	    }
	    
	    
	    int effectiveUserCount = 0;//有效评分用户数
	    float buildUnitScore = 0.0f;//有效建设单位评分总和
	    float constructUnitScore = 0.0f;//有效施工单位评分总和
	    float supervisorUnitScore = 0.0f;//有效监理单位评分总和
	    float designUnitScore = 0.0f;//有效设计单位评分总和
	    
	    
	    for(UserProject up: upList) {
	    	if(up.getStatus()==2) {
	    		effectiveUserCount++;
	    		List<ScoreHistory> list = ScoreHistoryHandler.getByUserIdProjectId(up.getUser().getId(), projectId);
	    		for(ScoreHistory history: list) {
	    			if(history.getTopCateId()==1) {//建设单位
	    				buildUnitScore += (history.getStandardScore()-history.getDecScore());
	    			}
	    			if(history.getTopCateId()==3) {//施工单位
	    				constructUnitScore += (history.getStandardScore()-history.getDecScore());
	    			}
	    			if(history.getTopCateId()==40) {//监理单位
	    				supervisorUnitScore += (history.getStandardScore()-history.getDecScore());
	    			}
	    			if(history.getTopCateId()==44) {//设计单位
	    				designUnitScore += (history.getStandardScore()-history.getDecScore());
	    			}
	    		}
	    	}
	    }
	    
	    entity.setStatus((short)2);//标记项目结束
	    entity.setEndTime(new Date());
	    
	    entity.setBuildUnitScore(buildUnitScore/effectiveUserCount);
	    entity.setConstructUnitScore(constructUnitScore/effectiveUserCount);
	    entity.setSupervisorUnitScore(supervisorUnitScore/effectiveUserCount);
	    entity.setDesignUnitScore(designUnitScore/effectiveUserCount);
	    
	    ProjectHandler.updateProject(entity);
	    
		request.setAttribute("message", "项目已经成功结束，评分结果已经生成。");
		request.setAttribute("nextURL", mapping.getInput());
		return mapping.findForward("tip");
	}	
	
	/**
	 *  管理员修改项目评分
	 */
	public ActionForward adminModifyScore(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception{
		int treeId = RequestUtil.getIntParameter(request, "treeId", 0);
		int projectId = RequestUtil.getIntParameter(request, "projectId", 0);
		int viewUserId = RequestUtil.getIntParameter(request, "viewUserId", 0);
		Project p = ProjectHandler.getProject(projectId);
		if(p.getStatus()!=2) {
			request.setAttribute("message", "项目结束前不可以修改用户评分");
			request.setAttribute("returnURL", mapping.getInput()+ "?projectId="+projectId+"&uid="+viewUserId+"");
			return mapping.findForward("fail");		
		}		
		User user = (User) request.getSession().getAttribute("user");
		if(user.getAuthority()!=UserKey.Authority_Admin) {
			request.setAttribute("message", "非管理员不可修改用户评分");
			request.setAttribute("returnURL", mapping.getInput() + "?projectId="+projectId+"&uid="+viewUserId+"");
			return mapping.findForward("fail");	
		}
		
		UserProject userProject = UserProjectHandler.getUserProjectByUidPid(viewUserId, projectId);
		if(userProject.getStatus()!=2) {//用户评分完成
			request.setAttribute("message", "要修改的用户没有完成评分，评分无效");
			request.setAttribute("returnURL", mapping.getInput() + "?projectId="+projectId+"&uid="+viewUserId+"");
			return mapping.findForward("fail");
		}
		
		List<ProjectItems> projectItemsList = ProjectItemsHandler.getByProjectIdTreeId(projectId, treeId);
		for(int i=0; i<projectItemsList.size(); i++) {
			ProjectItems item = projectItemsList.get(i);
			ScoreHistory history = ScoreHistoryHandler.getByUidPidPitemId(viewUserId,projectId,item.getScoreItem().getId());
			if(history==null) {
				history = new ScoreHistory();
				history.setProjectId(projectId);
				history.setProjectItemId(item.getScoreItem().getId());
				history.setStandardScore(item.getScore());
				history.setTopCateId(item.getTopCateId());
				history.setUser(UserHandler.getUser(viewUserId));				
			}
			history.setDecScore(RequestUtil.getFloatParameter(request, "decScore_" + item.getScoreItem().getId(), 0));
			int historyId = ScoreHistoryHandler.save(history);
			history.setId(historyId);
			logger.info("Admin(" + user.getId() + ") modify user(" + viewUserId + ") ScoreHistory(" + history.toString() + ")");
		}
		
	    //获得用户项目表，找到所有已评完分的用户，计算他们的评分值，根据人数得出评分的平均值
	    Set<UserProject> upList = p.getUserProjects();
	    int effectiveUserCount = 0;//有效评分用户数
	    float buildUnitScore = 0.0f;//有效建设单位评分总和
	    float constructUnitScore = 0.0f;//有效施工单位评分总和
	    float designUnitScore = 0.0f;//有效设计单位评分总和
	    float supervisorUnitScore = 0.0f;//有效监理单位评分总和
	    
	    for(UserProject up: upList) {
	    	if(up.getStatus()==2) {
	    		effectiveUserCount++;
	    		List<ScoreHistory> list = ScoreHistoryHandler.getByUserIdProjectId(up.getUser().getId(), projectId);
	    		if(up.getUser().getId()==viewUserId) {//当前修改的用户，同时更新它的评分
	    		    float userBuildUnitScore = 0.0f;//有效建设单位评分总和
	    		    float userConstructUnitScore = 0.0f;//有效施工单位评分总和
	    		    float userSupervisorUnitScore = 0.0f;//有效监理单位评分总和
	    		    float uesrDesignUnitScore = 0.0f;//有效设计单位评分总和
	    		    
	    			List<ScoreHistory> scoreList = ScoreHistoryHandler.getByUserIdProjectId(user.getId(), projectId);
	    			for(ScoreHistory history: scoreList) {
	    				if(history.getTopCateId()==1) {//建设单位
	    					userBuildUnitScore += (history.getStandardScore()-history.getDecScore());
	    				}
	    				if(history.getTopCateId()==3) {//施工单位
	    					userConstructUnitScore += (history.getStandardScore()-history.getDecScore());
	    				}
	    				if(history.getTopCateId()==40) {//监理单位
	    					userSupervisorUnitScore += (history.getStandardScore()-history.getDecScore());
	    				}	    				
	    				if(history.getTopCateId()==44) {//设计单位
	    					uesrDesignUnitScore += (history.getStandardScore()-history.getDecScore());
	    				}
	    			}
	    			up.setBuildUnitScore(userBuildUnitScore);
	    		    up.setConstructUnitScore(userConstructUnitScore);
	    		    up.setSupervisorUnitScore(userSupervisorUnitScore);
	    		    up.setDesignUnitScore(uesrDesignUnitScore);
	    		    UserProjectHandler.save(up);
	    		}
    			//计算用户的总分
	    		for(ScoreHistory history: list) {
	    			if(history.getTopCateId()==1) {//建设单位
	    				buildUnitScore += (history.getStandardScore()-history.getDecScore());
	    			}
	    			if(history.getTopCateId()==3) {//施工单位
	    				constructUnitScore += (history.getStandardScore()-history.getDecScore());
	    			}
	    			if(history.getTopCateId()==40) {//监理单位
	    				supervisorUnitScore += (history.getStandardScore()-history.getDecScore());
	    			}
	    			if(history.getTopCateId()==44) {//设计单位
	    				designUnitScore += (history.getStandardScore()-history.getDecScore());
	    			}
	    		}
	    	}
	    }
	    
	    p.setBuildUnitScore(buildUnitScore/effectiveUserCount);
	    p.setConstructUnitScore(constructUnitScore/effectiveUserCount);
	    p.setSupervisorUnitScore(supervisorUnitScore/effectiveUserCount);
	    p.setDesignUnitScore(designUnitScore/effectiveUserCount);
	    
	    ProjectHandler.updateProject(p);
		
		request.setAttribute("message", "修改成功,项目评分已经重新计算");
		request.setAttribute("nextURL", mapping.getInput() + "?projectId=" + projectId + "&treeId=" + treeId+"&uid=" + viewUserId);
		return mapping.findForward("tip");
	}	
}